import { saveAs } from "file-saver-fixed";
import html2canvas from "html2canvas";
import xlsx from 'node-xlsx';
//转换为utf8数据流
function convertBase64UrlToBlob(base64) {
  var parts = base64.split(";base64,");
  var contentType = parts[0].split(":")[1];
  var raw = window.atob(parts[1]);
  var rawLength = raw.length;
  var uInt8Array = new Uint8Array(rawLength);
  for (var i = 0; i < rawLength; i++) {
    uInt8Array[i] = raw.charCodeAt(i);
  }
  return new Blob([uInt8Array], { type: contentType });
}
/***
 * obj为要导出内容Element
 */
function exportImage(obj,option) {
  
  
    var op={
        allowTaint: true,//允许加载跨域的图片
        tainttest: false, //检测每张图片都已经加载完成
        useCORS:true,
        width:obj.offsetWidth,
        height:obj.offsetHeight,
        // windowWidth:obj.offsetWidth,
        // windowHeight:obj.scrollHeight
      };
      if(option){
      for(var key in option){
        op[key]=option[key];
      }
      }

  html2canvas(obj, op).then(function(canvas) {
    var image = canvas.toDataURL("image/jpeg");
    var blob = convertBase64UrlToBlob(image);
    saveAs(blob, new Date().getTime() + ".jpg");
  });
}
/***
 * 导出表格xls
 * title格式=>[1,2,3,3,4452354,3434,'hello',true]
 * ,tableList格式=>[[11,33,4,54,54545,66],
 * [11,33,4,54,54545,66],
 * [11,33,4,54,54545,66],
 * [11,33,4,54,54545,66]]
 *  */
function exportTable(title,tableList){
    
    var data = tableList;    
    data.unshift(title);
    var buffer = xlsx.build([{name: "mySheetName", data: data}]); // Returns a buffer
    var blob = new Blob([buffer],{type: 'application/vnd.ms-excel,charset=UTF-8',});
    saveAs(blob, new Date().format('yyyyMMddhhmmss') + '.xls');
}
//生成表格数据
function exportTable1(title,tableList){
  var t=[],list=[];
    for(var i=0;i<title.length;i++){
      t.push(title[i].name);
    }
    for(var i=0;i<tableList.length;i++){
      var item=[];
      for(var j=0;j<title.length;j++){
        item.push(tableList[i][title[j].code]);       
      }
      list.push(item);
    }
 exportTable(t,list);
}
function exportFile(file,ex,type){
 
  var blob = new Blob([file],{type: type+',charset=UTF-8',});
    saveAs(blob, new Date().format('yyyyMMddhhmmss') + ex);
}
export default{
  exportImage,
  exportTable,
  exportTable1,
  exportFile
};
